package org.example.j1110nm2;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.Arrays;

@RestController
@RequestMapping("/test04")
public class Test04 {
    //传统方式访问获取cookie
    @RequestMapping("/r1")
    //下面的两个参数是我们的内置对象
    public String r1(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();

        //下面的这个是我们的lambda表达式的写法
//        Arrays.stream(cookies).forEach(cookie -> {
//            System.out.println(cookie.getName() + " : " + cookie.getValue());
//        });
        if(cookies != null){
            for(Cookie c:cookies){
                System.out.println(c.getName()+":"+c.getValue());
            }
            return "获取成功";
        }

        return "cookie是空的";

    }

    @RequestMapping("/r2")
    //下面的两个参数是我们的内置对象
    public String r2(@CookieValue("bite") String bite) {
        return bite;
    }

    @RequestMapping("/r3")
    public String r3(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("username","zhangsan");
        return "设置session成功";
    }

    @RequestMapping("/r4")
    public String r4(HttpServletRequest request){
        HttpSession session = request.getSession();
        String username = (String)session.getAttribute("username");
        return "登录用户"+username;
    }

    @RequestMapping("/r5")
    //下面的这个里面的参数也是我们的内置对象
    public String r5(HttpSession session){
        String username = (String)session.getAttribute("username");
        return "登录用户"+username;
    }

    @RequestMapping("/r6")
    public String r6(@SessionAttribute(value = "username",required = false) String username){
        return "登录用户"+username;
    }
}
